package com;

/**
 * @author zw
 * @date 2022-06-27.
 */
import okhttp3.*;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ApiRequestDemo {
    static final String APP_ID = "1180";
    static final String APP_SECRET = "cf6a4ffc914b0f9d7c5adc2cba711114";

    public static void main(String[] args) throws IOException {

        /**
         * 这里的code 要用于计算sign值，必须是还原成明文。
         * 部分 sign 异常原因是因为 code 值为 base64加密串或encodeURIComponent未被还原造成的
         */
        String code = "class Main {\n" +
                "\tpublic static void main(String[] args) {\n" +
                "        //JSRUN引擎2.0，支持多达30种语言在线运行，全仿真在线交互输入输出。\n" +
                "\t\tSystem.out.println(\"Hello JSRUN!   \\n\\n         - from JAVA .\");\n" +
                "\t}\n" +
                "}";
        String input= "";//所传代码无需输入时， 此参数传空
        String sign = sign(code,input);
        String lang = "java";

        // post 请求
        FormBody body = new FormBody.Builder()
                .add("appId", APP_ID)
                .add("sign", sign)
                .add("lang", lang)
                .add("code", URLEncoder.encode(Base64Util.encode(code)))
                .add("input", URLEncoder.encode(Base64Util.encode(input)))
                .build();
        String result = post("http://jsrun.net/api/run/v2", body);
        System.out.print(result);
    }

    static String sign(String code,String input) {
        return md5(code + input + APP_SECRET);
    }

    static String md5(String str) {
        /**
         * Spring 中建议直接使用 DigestUtils.md5DigestAsHex() 计算md5值
         */
        try {
            byte[] secretBytes = null;
            secretBytes = MessageDigest.getInstance("md5").digest(str.getBytes());

            String md5code = new BigInteger(1, secretBytes).toString(16);
            for (int i = 0; i < 32 - md5code.length(); i++) {
                md5code = "0" + md5code;
            }
            return md5code;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
    }

    static String post(String url, RequestBody body) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(body).build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}